<script setup lang="ts">
interface Props {
  items?: any[] // Add optional modifier
  direction?: 'left' | 'right' // 滚动方向
  speed?: number // 动画速度（单位秒）
  className?: string // 自定义类名
  rootName?: string // 自定义根类名
}
const router = useRouter()

const props = withDefaults(defineProps<Props>(), {
  items: () => [],
  direction: 'left',
  speed: 20,
})

const emit = defineEmits(['callback'])

const containerRef = ref<HTMLElement>()

// 悬停状态
const isHovered = ref(false)
const handleMouseEnter = () => (isHovered.value = true)
const handleMouseLeave = () => (isHovered.value = false)

// 点击图片
const handleClick = (item: any, items: any) => {
  router.push(`/details/${item.name}`)
  emit('callback', item, items)
}

const contentRef = ref<HTMLElement>()
const isAnimationNeeded = ref(false)

// 计算动画参数
const animationStyle = computed(() => ({
  '--duration': `${props.speed}s`,
  '--direction': props.direction === 'left' ? 'normal' : 'reverse',
  '--translate': isAnimationNeeded.value ? '-50%' : '0',
}))

// 检查是否需要滚动
const checkScrollNeeded = () => {
  if (contentRef.value && containerRef.value) {
    const contentWidth = contentRef.value.scrollWidth / 2 // 因为我们复制了一份内容
    const containerWidth = containerRef.value.clientWidth
    isAnimationNeeded.value = contentWidth > containerWidth
  }
}

// 监听容器尺寸变化
const resizeObserver = new ResizeObserver(() => {
  checkScrollNeeded()
})

onMounted(() => {
  if (containerRef.value) {
    resizeObserver.observe(containerRef.value)
  }
  // 初始检查
  checkScrollNeeded()
})

// 监听items变化
watch(
  () => props.items,
  () => {
    nextTick(() => {
      checkScrollNeeded()
    })
  },
  { deep: true }
)

onBeforeUnmount(() => {
  resizeObserver.disconnect()
})
</script>

<template>
  <div
    ref="containerRef"
    class="scroll-container"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
  >
    <div
      ref="contentRef"
      class="scroll-content"
      :class="[rootName, { 'no-animation': !isAnimationNeeded }]"
      :style="{
        ...animationStyle,
        animationPlayState: isHovered ? 'paused' : 'running',
      }"
    >
      <div
        v-for="(item, index) in items?.length ? [...items, ...items] : []"
        :key="index"
        class="scroll-item"
        :class="className"
        @click="handleClick(item, items)"
      >
        <LazyImg
          :lazy="false"
          :src="item.logo"
          class="h-full w-full cursor-pointer object-cover"
          :alt="item.name"
          :title="item.name"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.scroll-container {
  @apply w-full overflow-hidden;
}

.scroll-content {
  @apply inline-flex items-center gap-1;
  animation: scroll var(--duration) linear infinite;
  animation-direction: var(--direction);
}

.no-animation {
  animation: none !important;
}

.scroll-item {
  @apply w-20 flex-shrink-0 transform-gpu transition-all duration-300 hover:-translate-y-1.5 hover:shadow-lg; /* 基础尺寸 */
  will-change: transform;
  border-radius: 15px;
  overflow: hidden;
  /* 添加硬件加速优化 */
  backface-visibility: hidden;
  perspective: 1000px;
}
@keyframes scroll {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(var(--translate, -50%));
  }
}
</style>
